<template>
  <button
    class="el-button"
    @click="handleClick"
    :disabled="buttonDisabled || loading"
    :autofocus="autofocus"
    :type="nativeType"
    :class="[
      type ? 'el-button--' + type : '',
      buttonSize ? 'el-button--' + buttonSize : '',
      {
        'is-disabled': buttonDisabled,
        'is-loading': loading,
        'is-plain': plain,
        'is-round': round,
        'is-circle': circle,
      },
    ]"
  >
    <i class="el-icon-loading" v-if="loading"></i>
    <i :class="icon" v-if="icon && !loading"></i>
    <span v-if="$slots.default"><slot></slot></span>
  </button>
</template>
<script>
import {computed, getCurrentInstance, inject, toRefs, unref} from 'vue';
const usebuttonSize = (size) => {
  const elFormItem = inject('elFormItem', {});

  const _elFormItemSize = computed(() => {
    return unref(elFormItem.elFormItemSize);
  });
  const buttonSize = computed(() => {
    return (
      size.value ||
      _elFormItemSize.value ||
      getCurrentInstance().ctx._elFormItemSize
    );
  });
  return buttonSize;
};
const userButtonDisabled = (disabled) => {
  const elForm = inject('elForm', {});

  const buttonDisabled = computed(() => {
    return disabled.value || elForm.disabled;
  });
  return buttonDisabled;
};
export default {
  name: 'ElButton',

  inject: {
    elForm: {
      default: '',
    },
    elFormItem: {
      default: '',
    },
  },

  props: {
    type: {
      type: String,
      default: 'default',
    },
    size: {
      type: String,
      default: '',
    },
    icon: {
      type: String,
      default: '',
    },
    nativeType: {
      type: String,
      default: 'button',
    },
    loading: Boolean,
    disabled: Boolean,
    plain: Boolean,
    autofocus: Boolean,
    round: Boolean,
    circle: Boolean,
  },

  computed: {
    _elFormItemSize() {
      return (this.elFormItem || {}).elFormItemSize;
    },
    // buttonSize() {
    //   return this.size || this._elFormItemSize || (this.$ELEMENT || {}).size;
    // },
    // buttonDisabled() {
    //   return this.disabled || (this.elForm || {}).disabled;
    // },
  },

  methods: {
    // handleClick(evt) {
    //   this.$emit('clicked', evt);
    // },
  },
  setup(props, {emit}) {
    const handleClick = (evt) => {
      emit('clicked', evt);
    };
    const {disabled, size} = toRefs(props);
    // 重构butonDisabled属性
    const buttonDisabled = userButtonDisabled(disabled);

    // 重构buttonSize属性

    const buttonSize = usebuttonSize(size);
    return {
      handleClick,
      buttonDisabled,
      buttonSize,
    };
  },
};
</script>
